{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "\n",
    "## 2016美国总统大选数据统计\n",
    "数据地址：https://www.kaggle.com/fivethirtyeight/2016-election-polls"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import datetime"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "datetime.datetime(2015, 10, 23, 0, 0)"
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "datetime.datetime.strptime('10/23/2015','%m/%d/%Y')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "datetime.datetime"
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(datetime.datetime.strptime('10/23/2015','%m/%d/%Y'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "\n",
    "def load_data(filename, use_cols):\n",
    "    \"\"\"\n",
    "        读取指定列的CSV数据\n",
    "    \"\"\"\n",
    "    # 读取列名，即第一行数据\n",
    "    with open(filename, 'r') as f:\n",
    "        col_names_str = f.readline()[:-1]  # [:-1]表示不读取末尾的换行符'\\n'\n",
    "\n",
    "    # 将字符串拆分，并组成列表\n",
    "    col_name_lst = col_names_str.split(',')\n",
    "\n",
    "    # 获取相应列名的索引号\n",
    "    use_col_index_lst = [col_name_lst.index(use_col_name) for use_col_name in use_cols]\n",
    "\n",
    "    # 读取数据\n",
    "    data_array = np.loadtxt(filename,       # 文件名\n",
    "                            delimiter=',',  # 分隔符\n",
    "                            skiprows=1,     # 跳过第一行，即跳过列名\n",
    "                            dtype=str,      # 数据类型\n",
    "                            usecols=use_col_index_lst)  # 指定读取的列索引号\n",
    "    return data_array\n",
    "\n",
    "\n",
    "def process_date(data_array):\n",
    "    \"\"\"\n",
    "        处理日期格式数据，转换为yyyy-mm字符串\n",
    "    \"\"\"\n",
    "    enddate_lst = data_array[:, 0].tolist()\n",
    "\n",
    "    # 将日期字符串格式统一，即'yy/dd/mm'\n",
    "    enddate_lst = [enddate.replace('-', '/') for enddate in enddate_lst]\n",
    "\n",
    "    # 将日期字符串转换成日期\n",
    "    date_lst = [datetime.datetime.strptime(enddate, '%m/%d/%Y') for enddate in enddate_lst]\n",
    "\n",
    "    # 构造年份-月份列表\n",
    "    month_lst = ['{}-{:02d}'.format(date_obj.year, date_obj.month) for date_obj in date_lst]\n",
    "\n",
    "    month_array = np.array(month_lst)\n",
    "\n",
    "    data_array[:, 0] = month_array\n",
    "    \n",
    "    return data_array\n",
    "\n",
    "\n",
    "def get_month_stats(data_array):\n",
    "    \"\"\"\n",
    "        统计每月的投票数据\n",
    "    \"\"\"\n",
    "    months = np.unique(data_array[:, 0])\n",
    "    for month in months:\n",
    "        # 根据月份过滤数据\n",
    "        filtered_data = data_array[data_array[:, 0] == month]\n",
    "\n",
    "        # 获取投票数据，字符串数组转换为数值型数组\n",
    "        try:\n",
    "            filtered_poll_data = filtered_data[:, 1:].astype(float)\n",
    "        except ValueError:\n",
    "            # 遇到不能转换为数值的字符串，跳过循环\n",
    "            continue\n",
    "\n",
    "        result = np.sum(filtered_poll_data, axis=0)\n",
    "\n",
    "        # 在列方向求和\n",
    "        print('{}，Clinton票数：{}，Trump票数：{}'.format(month, result[0], result[1]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2015-11，Clinton票数：1920.0，Trump票数：1948.2\n",
      "2015-12，Clinton票数：4816.799999999999，Trump票数：4164.299999999999\n",
      "2016-01，Clinton票数：6861.600076850002，Trump票数：6267.0\n",
      "2016-02，Clinton票数：8271.600253600001，Trump票数：7528.200000000002\n",
      "2016-03，Clinton票数：11656.202546，Trump票数：9626.699999999999\n",
      "2016-04，Clinton票数：11911.803926800001，Trump票数：9396.300000000005\n",
      "2016-07，Clinton票数：22007.013854599994，Trump票数：21426.99\n",
      "2016-08，Clinton票数：63619.39624199996，Trump票数：59529.000000000015\n"
     ]
    }
   ],
   "source": [
    "    \"\"\"\n",
    "        主函数\n",
    "    \"\"\"\n",
    "    filename='presidential_polls.csv'\n",
    "    # 读取指定列的数据\n",
    "    use_cols = ['enddate', 'rawpoll_clinton', 'rawpoll_trump']\n",
    "    data_array = load_data(filename, use_cols)\n",
    "\n",
    "    # 处理日期格式数据，转换为yyyy-mm字符串\n",
    "    proc_data_array = process_date(data_array)\n",
    "\n",
    "    # 统计每月的投票数据\n",
    "    get_month_stats(proc_data_array)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3 (ipykernel)"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}